package com.difsonapps.android.marker;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Cache;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.JsonObjectRequest;
import com.difsonapps.android.marker.adapters.LikesListAdapter;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.Like;
import com.difsonapps.android.marker.beans.Photo;
import com.difsonapps.android.marker.beans.Video;
import com.difsonapps.android.marker.util.MarkerUtil;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

public class LikesActivity extends Activity {
    private static final String TAG = LikesActivity.class.getSimpleName();
	Photo photo; //Photo concerned by the like
	Video video; //Photo concerned by the like
	ListView likesListView;
	EditText likeCommentEditText;
	Button publishButton;
	Button cancelButton;
	LinearLayout loadingStatusLayout;
	
	TextView count_likes;

    private LikesListAdapter likesAdapter;
    private List<Like> likes;
	
	
	int currentValue = -1;
	private int offset = 0;
	private int limit = 5;
	private boolean canContinue = true;
	private boolean loading2 = false;
    String avgSym = "";
    String no_like = "";
    String lab_like = "";
    String lab_likes = "";
    
    String now = "";
    
    int countLikesValue;
    boolean iLikeValue;
    
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//toast("Closing...");
    	close();
		return true;
	}
    
    private void close(){
    	Intent result = new Intent();
		if(photo!=null) result.putExtra("photo", photo);
		if(video!=null) result.putExtra("video", video);
		result.putExtra("nb_likes", countLikesValue);
		result.putExtra("count_likes", countLikesValue);
		result.putExtra("i_like", iLikeValue);
		setResult(RESULT_OK, result);
		finish();
    }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_likes);
		getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.main_color)));

        avgSym = getResources().getString(R.string.avg_sym);
        no_like = getResources().getString(R.string.no_like);
        lab_like = getResources().getString(R.string.like);
        lab_likes = getResources().getString(R.string.likes);
        
        count_likes = (TextView)findViewById(R.id.nb_likes);
        
		likesListView = (ListView)findViewById(R.id.likesListView);
		
		
		publishButton = (Button)findViewById(R.id.publishButton);
		cancelButton = (Button)findViewById(R.id.cancelButton);
		loadingStatusLayout = (LinearLayout)findViewById(R.id.loadingStatusLayout0);
		
		likes = new ArrayList<Like>();
		 
		likesAdapter = new LikesListAdapter(this, likes);
		likesListView.setAdapter(likesAdapter);
        
		likesListView.setOnScrollListener(new EndlessScrollListener(1));
		
		Intent i = getIntent();
		photo = i.getParcelableExtra("photo");
		video = i.getParcelableExtra("video");
		if(photo!=null){
			showLikeStats(photo.getNbLikes());
		}
		else if(video!=null){
			showLikeStats(video.getCountLikes());
		}
		
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		
		/*publishButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				publish();
			}
		});
		cancelButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				cancel();
			}
		});*/
		
		loadLikes();
	}

	public void showLikeStats(int nb){
		count_likes.setText(nb==0?no_like:(""+nb+" "+(nb==1?lab_like:lab_likes)));
	}


	public void btnPublishClick(View v){
		publish();
	}
	public void btnCloseClick(View v){
		cancel();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.likes, menu);
		return true;
	}
	
	private void toast(String text){
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
	
	private void publish(){
		Map<String, String> params = new HashMap<String, String>();
        params.put("id", ""+photo.getId());//TODO Put the id of the image selected here
        params.put("subject", "photo");


		showProgress();
		
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				AppConstant.likeUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	hideProgress();
                    	//toast("Response : "+response.toString());
                    	parseJsonPostLike(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	hideProgress();
                    	toast("Error: " + error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	private void cancel(){
		this.finish();
	}
	
	private void loadLikes(){
		Cache cache = AppController.getInstance().getRequestQueue().getCache();
    	if(!canContinue) return;
    	Map<String, String> params = new HashMap<String, String>();
    	params.put("id", ""+(photo==null?(video==null?0:video.getId()):photo.getId()));
        params.put("offset", ""+offset);
        params.put("limit", ""+limit);
        String url = MarkerUtil.buildUrl(video!=null?AppConstant.listVideoLikesUrl:AppConstant.listPhotoLikesUrl, params);
        //toast("URL : "+url);
        Entry entry = cache.get(url);
        if (entry != null) {
            // fetch the data from cache
            try {
                String data = new String(entry.data, "UTF-8");
                try {
                    parseJsonLikes(new JSONObject(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
 
        } else {
            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
            		url, null, new Response.Listener<JSONObject>() {
 
                        @Override
                        public void onResponse(JSONObject response) {
                            VolleyLog.d(TAG, "Response: " + response.toString());
                            if (response != null) {
                                parseJsonLikes(response);
                            }
                        }
                    }, new Response.ErrorListener() {
 
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                        }
                    });
 
            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
            if(offset==0) showProgress();//au premier chargement on affiche le progress bar
            loading2=true;
        }
	}
        
        private void parseJsonLikes(JSONObject response) {
        	//toast("Response : "+response.toString());
            try {
                JSONArray feedArray = response.getJSONArray("likes");
                if(feedArray.length()==0) canContinue=false;
                
                if(response.has("count_likes")){
                	iLikeValue = response.has("i_like")?response.getBoolean("i_like"):false;
                	countLikesValue = response.getInt("count_likes");
                	showLikeStats(countLikesValue);
                }
                if(("".equals(now))&&response.has("now")){
                	now = response.getString("now");
                }
     
                for (int i = 0; i < feedArray.length(); i++) {
                	//toast("Loading item "+i);
                    JSONObject feedObj = (JSONObject) feedArray.get(i);
                	Like item = Like.parseFromJsonObject(feedObj);
                    item.setRelativeDate(MarkerUtil.getRelativeTime(item.getCreated_at(), now, this));
                	if(offset==0 || offset>item.getId()) offset = item.getId();
                    likes.add(item);
                }
     
                // notify data changes to list adapater
                likesAdapter.notifyDataSetChanged();
                
                hideProgress();
                //loadingStatusLayout.setVisibility(View.GONE);
                //likesListView.setVisibility(View.VISIBLE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            loading2 = false;
        }
        
        private void parseJsonPostLike(JSONObject response) {
            try {
            	//toast(response.toString());
                if(response.has("success")){
                	String success = response.getString("success");
                	//toast(success);
                    
                    if(response.has("count_likes")){
                    	iLikeValue = response.has("i_like")?response.getBoolean("i_like"):false;
                    	countLikesValue = response.getInt("count_likes");
                    	showLikeStats(countLikesValue);
                    }
                    if(("".equals(now))&&response.has("now")){
                    	now = response.getString("now");
                    }
                	if(response.has("like")){
                		JSONObject feedObj = response.getJSONObject("like");
                    	Like item = Like.parseFromJsonObject(feedObj);
                        item.setRelativeDate(MarkerUtil.getRelativeTime(item.getCreated_at(), now, this));
                	     
                        likes.add(0, item);
                        likesAdapter.notifyDataSetChanged();
                	}
                	//int uid = response.getInt("uid");
                	//String firstname = response.getString("firstname");
                	
    				
                	//toast("User id : "+uid);
                }else if(response.has("error")){
                	String error = response.getString("error");
                	//loginErrorView.setText(error);
                	//loginErrorView.setVisibility(View.VISIBLE);
                	//TODO Show the error message in a textView and make it visible
                	toast(error);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        

        
        class EndlessScrollListener implements OnScrollListener {

            private int visibleThreshold = 5;
            private int currentPage = 0;
            private int previousTotal = 0;
            private boolean loading = true;

            public EndlessScrollListener() {
            }
            public EndlessScrollListener(int visibleThreshold) {
                this.visibleThreshold = visibleThreshold;
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {
                if (loading) {
                    if (totalItemCount > previousTotal) {
                        loading = false;
                        previousTotal = totalItemCount;
                        currentPage++;
                    }
                }
                if ((!loading) &&(!loading2) && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
                    // I load the next page of gigs using a background task,
                    // but you can call any function here.
                	loadLikes();
                    /*new LoadGigsTask().execute(currentPage + 1);
                    loading = true;*/
                }
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }
        }
        
        ProgressDialog loadingProgressDialog;
        private void hideProgress(){
        	if(loadingProgressDialog!=null) loadingProgressDialog.dismiss();
        	//hideProgress();
        }
        private void showProgress(){
            loadingProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.loading), getResources().getString(R.string.loading), true);
            loadingProgressDialog.setCancelable(true);
        	//showProgress(true);
        }
        private void showProgress(boolean state){
        	loadingStatusLayout.setVisibility(state?View.VISIBLE:View.GONE);
            likesListView.setVisibility(state?View.GONE:View.VISIBLE);
        }

}
